package lottery;

import inc.CommonFunction;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import reflect.ReflectObject;
import code.lewdy.app.notice.Notice;
import code.lewdy.app.user.AccountRecord;
import code.lewdy.db.Database;
import code.lewdy.db.HibernateTemple;
import code.lewdy.db.JdbcUtil;
import code.lewdy.lottery.LotteryRewardCount;
import code.lewdy.lottery.LotteryService;
import code.lewdy.lottery.LotteryTimeManager;
import code.lewdy.lottery.OpenRewardNumber;
import code.lewdy.util.DataType;
import code.lewdy.web.PassportUtil;
import code.lewdy.web.request.ExtRequest;
import code.lewdy.web.response.ExtResponse;
import code.lewdy.xml.XMLUtil;

import com.lt.member.Member;
import com.lt.member.MemberStatistics;
import com.opensymphony.xwork2.ActionSupport;

public class LotteryAction extends ActionSupport implements
		ServletResponseAware, ServletRequestAware{
	private CommonFunction fun = new CommonFunction();
	LotteryService ls = new LotteryService();
	private HttpServletRequest req;
	private HttpServletResponse resp;
	private ExtRequest extreq = null;
	private JdbcUtil jdbc = new JdbcUtil(Database.TYPE_SQLSERVER);
	private String classPath;
	private int lotteryId;
	private int dataId;
	private String condition;
	private String ext1; //扩展字段


	public static void main(String[] args) {

	}
	
	/**按期号派奖
	 * ext1为期号
	 * @return
	 */
	public String doPayByNumberId(){
		String msg = "派奖成功！";
		int results = 1;
		String sql = "SELECT * from BetRecord where numberId = '"+ext1+
			"' or orderId = '"+ext1+"'";
		List<BetRecord> brs = (List<BetRecord>) jdbc.list("lottery.BetRecord", 
				"where numberId = '"+ext1+"' or orderId = '"+ext1+"'", 1, 10000);
		for(BetRecord br : brs){
			if(br == null){
				ExtResponse.error(resp, "派奖失败：要指派的投注记录不存在！", DataType.XML);
				return null;
			}
			PayReward pay = new PayReward();
			results = pay.doPay(br);
			switch (results) {
				case 1:msg="派奖成功！";break;
				case -2:msg="已经派奖,不能重复派奖!";break;
				case -3:msg="已经撤单，无效定单!";break;
				case -4:msg="投注号码为空!";break;
				case -5:msg="开奖号码为空!";break;
				default:
					break;
			}
		}
		if(results == 1)
			ExtResponse.ok(resp, msg, DataType.XML);
		else
			ExtResponse.error(resp, msg, DataType.XML);
		return null;
	}
	
	/**团队管理>获取自己的下级信息
	 * @return
	 */
	public String getTeammate(){
		String condition = "where fatherId = "+dataId +" order by id DESC ";
		int pageSize = extreq.getInt("pageSize")==0 ? 15 : extreq.getInt("pageSize");
        int page = extreq.getInt("page")==0 ? 1 : extreq.getInt("page");
        classPath = extreq.getString("classPath");
        condition = extreq.getString("condition")==null ? "" : extreq.getString("condition");
        HashMap map = null;
        Iterator keyIterator = null;
        String key = null;
        String results = fun.xmlAppend(null, null, "resp", null);
        List list = jdbc.list(classPath, condition, page, pageSize);
        if (list.size() > 0) {
            results = fun.xmlAppend(results, "resp", "list", null);
        }
        results = fun.xmlAppend(results, "resp", "size", list.size());
        results = fun.xmlAppend(results, "resp", "page", page);
        for (Object obj : list) {
            results = fun.xmlAppend(results, "list", "obj", null);
            map = ReflectObject.getFieldValues(obj, classPath);
            keyIterator = map.keySet().iterator();
            while (keyIterator.hasNext()) {
                key = (String) keyIterator.next();
                if(Notice.class.getName().equals(classPath) && key.equals("content")){
                	results = fun.xmlAppend(results, "obj", key, (""+map.get(key)).replace("<", "&lt;").replace(">", "&gt;"));
                }else{
                	results = fun.xmlAppend(results, "obj", key, map.get(key));
                }
            }
        }
        fun.ajaxPrint(resp, "xml", null, results);
        System.out.println("query:" + results);
        return null;
	}
	
	/**管理员无条件撤单
	 * @return
	 */
	public String cancelBetByAdmin() {
		BetRecord br = (BetRecord) HibernateTemple.load(BetRecord.class, dataId);
		if(br.getIsCancel() == 1){
			ExtResponse.error(resp, "不能重复撤单!",  "xml");
			return null;
		}else if(br.getIsPay() == 1){
			ExtResponse.error(resp, "操作失败：已派奖!",  "xml");
			return null;
		}
		double betAmount = br.getSingleAmount() * br.getCount();
		Member m = (Member) HibernateTemple.load(Member.class, br.getOwnerId());
		br.setIsCancel(1);
		m.setBalance(m.getBalance() + betAmount);
		HibernateTemple.update(m);
		HibernateTemple.update(br);

		//账变记录
		new AccountRecord().insert(m, br.getOrderId(), AccountRecord.GROUP_LOTTERY_BET_CANCEL, 
				betAmount, "撤消订单返额");
		ExtResponse.ok(resp, "撤单成功!",  "xml");
		return null;
	}
	
	/**
	 * 撤消投注 撤单
	 * 
	 * @return
	 * @author liuding,2012-5-18
	 */
	public String cancelBet() {
		BetRecord br = (BetRecord) HibernateTemple.load(BetRecord.class, dataId);
		int sessionUid = PassportUtil.getUserId(req);
		if(br.getOwnerId() != sessionUid){
			ExtResponse.error(resp, "只能撤自己的订单!",  "xml");
			return null;
		}
		if(br.getIsCancel() == 1){
			ExtResponse.error(resp, "不能重复撤单!",  "xml");
			return null;
		}else if(br.getIsPay() == 1){
			ExtResponse.error(resp, "操作失败：已派奖!",  "xml");
			return null;
		}else if(br.getIsUnion() == 1){
			ExtResponse.error(resp, "操作失败：合买不支持撤单!",  "xml");
			return null;
		}
		//开奖剩余秒数，开奖前1分钟停止撤单
		int openTimeLeft = ls.getOpenTimeLeft(br.getLotteryId());
		if(openTimeLeft < 60){
			ExtResponse.error(resp, "撤单失败：已超出当期撤单时间!",  "xml");
			return null;
		}
		long brNumberId = Long.parseLong(br.getNumberId().replace("-", ""));
		long currentNumberId = Long.parseLong(ls.getNewNumberId(br.getLotteryId()).replace("-", ""));
		if(currentNumberId > brNumberId){
			ExtResponse.error(resp, "撤单失败：已超出当期撤单时间!",  "xml");
			return null;
		}
		double betAmount = br.getSingleAmount() * br.getCount();
		Member m = (Member) HibernateTemple.load(Member.class, br.getOwnerId());
		br.setIsCancel(1);
		m.setBalance(m.getBalance() + betAmount);
		HibernateTemple.update(m);
		HibernateTemple.update(br);

		//账变记录
		new AccountRecord().insert(m, br.getOrderId(), AccountRecord.GROUP_LOTTERY_BET_CANCEL, 
				betAmount, "撤消订单返额");
		ExtResponse.ok(resp, "撤单成功!",  "xml");
		return null;
	}
	
	/**获取下次开奖剩余时间(秒)
	 * @return
	 */
	public String getNextRewardTimeLeft(){
		//int s = LotteryTimeManager.getRemainderTime(ext1);
		int s = ls.getOpenTimeLeft(lotteryId);
		ExtResponse.ok(resp, s+"", DataType.XML);
		//System.out.println(lotteryId+"开奖剩余时间:"+s);
		return null;
	}
	
	/*
	public String getNextRewardTimeLeft(){
		String msg = "";
		Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        int second = c.get(Calendar.SECOND);
        int secondCount = hour * 3600 + minute * 60 + second;
        Session s = HibernateSessionFactory.getSession();
        s.beginTransaction();
        ArrayList<RewardTime> list = (ArrayList<RewardTime>) s.createQuery(
                "from RewardTime rt where lotteryId = "+lotteryId+" and beginTime < " + secondCount + " and endTime > "
                        + secondCount).list();
        s.getTransaction().commit();
        if(list.size() == 0){
        	msg = "该时间段没有开奖信息！";
        	ExtResponse.error(resp, msg, DataType.XML);
        	return null;
        }
        RewardTime rt = list.get(0);
        //now
        int currentSp = rt.getOpenTimeSp() - (secondCount - rt.getBeginTime()) % rt.getOpenTimeSp();
        System.out.println("截止投注时间："+currentSp+"秒");
        s.close();
        ExtResponse.ok(resp, currentSp+"", DataType.XML);
		return null;
	}
	*/
	
	/**获取最新开奖号码对象
	 * @return
	 */
	public String getOpenRewardNumber(){
		OpenRewardNumber num = ls.getNewRewardNumber(lotteryId);
		String respText = XMLUtil.objectToXML(num);
		ExtResponse.outString(resp, respText, "xml");
		return null;
	}
	
	/**获取最新的开奖号码
	 * @return
	 */
	public String getOpenRewardNumberByLottery(){
		System.out.println("getOpenRewardNumberByLottery()");
		OpenRewardNumber num = ls.getNewRewardNumber(lotteryId);
		String number = num.getNumber();
		System.out.println(num.getLotteryName()+"-开奖号码："+number);
		ExtResponse.ok(resp, number, DataType.XML);
		return null;
	}
	
	/**
	 * 获得当前期号
	 * 
	 * @return
	 * @author liuding,2012-5-17
	 */
	public String getCurrentNumberID() {
		System.out.println("getCurrentNumberID()");
		String newNumber = ls.getNewNumberId(lotteryId);
		ExtResponse.ok(resp, newNumber, DataType.XML);
		return null;
	}

	public int getLotteryId() {
		return lotteryId;
	}

	public void setLotteryId(int lotteryId) {
		this.lotteryId = lotteryId;
	}

	public String getClassPath() {
		return classPath;
	}

	public void setClassPath(String classPath) {
		this.classPath = classPath;
	}

	public void setServletResponse(HttpServletResponse resp) {
		// TODO Auto-generated method stub
		this.resp = resp;
	}

	public int getDataId() {
		return dataId;
	}

	public void setDataId(int dataId) {
		this.dataId = dataId;
	}

	public void setServletRequest(HttpServletRequest req) {
		// TODO Auto-generated method stub
		this.req = req;
        if(extreq == null)
            extreq = new ExtRequest(this.req);
	}
	public String getExt1() {
		return ext1;
	}

	public void setExt1(String ext1) {
		this.ext1 = ext1;
	}

	public void setCondition(String condition) {
		this.condition = condition;
	}

	public String getCondition() {
		return condition;
	}
}
